import 'dart:async';
import 'dart:math';
import 'dart:ui';
import 'package:assets_audio_player/assets_audio_player.dart';
import 'package:e_reception_flutter/ui/new_terminal/bg_music/bean/bg_terminal_music_list_response_bean.dart';
import 'package:e_reception_flutter/ui/new_terminal/bg_music/bg_sys_recommend_music_view_model.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/select_smart_home_bgm_event.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/set_smart_home_folder_bgm_dialog.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_column_response_bean.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_publish_page.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_hud_utils.dart';
import 'package:e_reception_flutter/vg_widgets/light_annotated_region_style.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import '../smart_home_upload_service.dart';
import 'marquee.dart';

///发布图片效果展示页面
class SmartHomePublishImageShowPage extends StatefulWidget {
  ///路由名称
  static const String ROUTER = "SmartHomePublishImageShowPage";
  final String shid;
  final String type;
  final List<ColumnListBean> columnList;
  final ColumnListBean currentColumn;
  //上传完成后回到的页面
  final String router;
  final List<SmartHomeUploadItemBean> currentList;


  const SmartHomePublishImageShowPage({
    Key key,
    this.shid,
    this.type,
    this.columnList,
    this.currentColumn,
    this.router,
    this.currentList,
  }) : super(key: key);

  @override
  _SmartHomePublishImageShowPageState createState() =>
      _SmartHomePublishImageShowPageState();

  static Future<dynamic> navigatorPush(BuildContext context,
      String shid,
      String type,
      List<ColumnListBean> columnList,
      ColumnListBean currentColumn,
      {String router,List<SmartHomeUploadItemBean> currentList,}) {
    return RouterUtils.routeForFutureResult(
        context,
        SmartHomePublishImageShowPage(
          shid: shid,
          type: type,
          columnList: columnList,
          currentColumn: currentColumn,
          router: router,
          currentList: currentList,
        ),
        routeName: SmartHomePublishImageShowPage.ROUTER);
  }
}

class _SmartHomePublishImageShowPageState
    extends BaseState<SmartHomePublishImageShowPage> {
  BgSysRecommendMusicViewModel _musicViewModel;

  //要上传的数据
  List<SmartHomeUploadItemBean> _uploadList = List();
  int _selectIndex = 0;
  double _indexWidth;
  MusicListBean _currentBgm;

  List<MusicListBean> _musicList = List();
  AssetsAudioPlayer _assetsAudioPlayer;
  StreamSubscription _selectBgmStreamSubscription;
  bool _isPlaying = false;
  Audio _playingAudio;
  String _currentMusicId;
  bool _showMusicWidget = true;
  @override
  void initState(){
    super.initState();
    _assetsAudioPlayer = AssetsAudioPlayer.newPlayer();
    _assetsAudioPlayer.onReadyToPlay.listen((event) {
      VgHudUtils.hide(context);
    });
    _assetsAudioPlayer.isPlaying.listen((isPlay) {
      setState(() {
        _isPlaying = isPlay??false;
      });
    });
    _assetsAudioPlayer.current.listen((playing) {
      if(playing != null){
        setState(() {
          _currentMusicId = playing?.audio?.audio?.metas?.id??"";
          print('_currentMusicId : $_currentMusicId');
        });
      }
    });
    WidgetsBinding.instance.addObserver(this);
    _musicViewModel = new BgSysRecommendMusicViewModel(this, "");
    _indexWidth = 53;
    if (widget?.currentList != null && widget.currentList.isNotEmpty) {
      _uploadList.addAll(widget?.currentList);
    }
    _musicViewModel.musicListValueNotifier.addListener(() {
      if(_musicViewModel.musicListValueNotifier.value != null){
        _musicList.addAll(_musicViewModel.musicListValueNotifier.value);
        int index = Random().nextInt(_musicList.length);
        openPlayer(_musicList.elementAt(index));
      }
    });
    _musicViewModel.getBgByHsnWithoutCallback(context, "");
    _selectBgmStreamSubscription =
        VgEventBus.global.on<SelectSmartHomeBgmEvent>()?.listen((event) {
          if(event.musicListBean == null && event.cancelUse){
            setState(() {
              _currentBgm = null;
            });
          }else{
            if(_currentBgm == null){
              setState(() {
                _currentBgm = event.musicListBean;
              });
            }
          }
        });

  }


  @override
  Widget build(BuildContext context) {
    return LightAnnotatedRegion(
        child: Scaffold(
          resizeToAvoidBottomInset: false,
          resizeToAvoidBottomPadding: false,
          backgroundColor: Colors.black,
          body: _toMainWidget(),
        ));
  }

  @override
  void dispose() {
    super.dispose();
    _assetsAudioPlayer?.stop();
    _assetsAudioPlayer?.dispose();
    _selectBgmStreamSubscription?.cancel();
  }



  Widget _toMainWidget() {
    return Column(
      children: [
        _toTopBarWidget(),
        _toSwiper(),
        _toBottomWidget(),
      ],
    );
  }

  ///页面标题
  Widget _toTopBarWidget() {
    return VgTopBarWidget(
      isShowBack: true,
      rightPadding: 16,
      rightWidget: _toMusicStatusWidget(),
    );
  }

  Widget _toMusicStatusWidget(){
    return Opacity(
      opacity: _showMusicWidget?1:0,
      child: GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: ()async{
          if(_musicList.isEmpty){
            _musicViewModel.getBgByHsn(context, "", (musicList) async {
              _musicList.addAll(musicList);
              setState(() {
                _showMusicWidget = false;
              });
              MusicListBean musicListBean = await SetSmartHomeFolderBgmDialog.navigatorPushDialog(context, _musicList, _assetsAudioPlayer, _currentBgm?.id??"");
              if(musicListBean != null){
                if(musicListBean.id == (_currentBgm?.id??"")){
                  return;
                }
                openPlayer(musicListBean);
                setState(() {
                  _showMusicWidget = true;
                });
              }else{
                setState(() {
                  _showMusicWidget = true;
                });
                if(_currentBgm == null){
                  print("背景音乐无数据0");
                  if(_isPlaying){
                    _assetsAudioPlayer.stop();
                  }
                  return;
                }
                if(_currentMusicId == _currentBgm?.id){
                  print("啥都不干0");
                  return;
                }
                openPlayer(_currentBgm);
              }
            });
          }else{
            setState(() {
              _showMusicWidget = false;
            });
            MusicListBean musicListBean = await SetSmartHomeFolderBgmDialog.navigatorPushDialog(context, _musicList, _assetsAudioPlayer, _currentBgm?.id??"");
            if(musicListBean != null){
              if(musicListBean.id == (_currentBgm?.id??"")){
                return;
              }
              openPlayer(musicListBean);
              setState(() {
                _showMusicWidget = true;
              });
            }else{
              setState(() {
                _showMusicWidget = true;
              });
              if(_currentBgm == null){
                print("背景音乐无数据1");
                if(_isPlaying){
                  _assetsAudioPlayer.stop();
                }
                return;
              }
              if(_currentMusicId == _currentBgm?.id){
                print("啥都不干1");
                return;
              }
              openPlayer(_currentBgm);

            }

          }
        },
        child: _currentBgm == null?_toNoBgmWidget():_toHasBgmWidget(),
      ),
    );
  }

  ///无音乐布局
  Widget _toNoBgmWidget(){
    return Container(
      width: 92,
      height: 30,
      padding: EdgeInsets.only(left: 12),
      alignment: Alignment.centerLeft,
      decoration: BoxDecoration(
        color: Color(0X66555555),
        borderRadius: BorderRadius.circular(15),
      ),
      child: Row(
        children: [
          Image.asset(
            "images/icon_folder_bg.png",
            width: 12,
            height: 14,
          ),
          SizedBox(width: 8,),
          Text(
            "选择音乐",
            style: TextStyle(
              fontSize: 12,
              color: Colors.white,
              fontWeight: FontWeight.w600,
            ),
          ),
        ],
      ),
    );
  }

  ///有音乐布局
  Widget _toHasBgmWidget(){
    return Container(
      height: 30,
      padding: EdgeInsets.only(left: 12),
      alignment: Alignment.centerLeft,
      decoration: BoxDecoration(
        color: Color(0X66555555),
        borderRadius: BorderRadius.circular(15),
      ),
      child: Row(
        children: [
          Image.asset(
            "images/icon_folder_bg.png",
            width: 12,
            height: 14,
          ),
          SizedBox(width: 8,),
          Container(
            constraints: BoxConstraints(
                maxWidth: 100
            ),
            alignment: Alignment.centerLeft,
            child: Marquee(
              text: _currentBgm?.mname??"",
              style: TextStyle(
                fontSize: 12,
                color: Colors.white,
                fontWeight: FontWeight.w600,
              ),
              scrollAxis: Axis.horizontal,
              crossAxisAlignment: CrossAxisAlignment.center,
              blankSpace: 100.0,
              velocity: 20.0,
              pauseAfterRound: Duration(milliseconds: 1),
              startPadding: 10.0,
              accelerationDuration: Duration(seconds: 1),
              accelerationCurve: Curves.linear,
              decelerationDuration: Duration(milliseconds: 1),
            ),
          ),

          SizedBox(width: 8,),
          Container(
            width: 1,
            height: 30,
            color: Color(0X1AFFFFFF),
          ),
          GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: (){
              setState(() {
                _assetsAudioPlayer.stop();
                _currentBgm = null;
              });
            },
            child: Container(
              width: 40,
              alignment: Alignment.center,
              child: Image.asset(
                "images/icon_close_white.png",
                width: 10,
                height: 10,
              ),
            ),
          ),
        ],
      ),
    );
  }



  ///图片轮播
  Widget _toSwiper() {
    double width = ScreenUtils.screenW(context);
    double height = ScreenUtils.screenH(context) - 44 - ScreenUtils.getStatusBarH(context) - 56 - ScreenUtils.getBottomBarH(context);
    return Container(
      width: width,
      height: height,
      alignment: Alignment.center,
      child:
      Stack(
        children: [
          Swiper(
            layout: SwiperLayout.DEFAULT,
            loop: (_uploadList?.length??0) > 1,
            itemBuilder: (BuildContext context, int index) {
              return _toSwiperItemWidget(_uploadList?.elementAt(index));
            },
            index: _selectIndex,
            itemCount: _uploadList?.length,
            autoplay: true,
            onIndexChanged: (index){
              _selectIndex = index;
              setState(() {});
            },
          ),
          Positioned(
            bottom: 0,
            child: _toIndexWidget(),
          )
        ],
      ),
    );
  }
  ///图片item
  Widget _toSwiperItemWidget(SmartHomeUploadItemBean item){
    BoxFit boxFit = BoxFit.contain;
    double screenWidth = ScreenUtils.screenW(context);
    double screenHeight = ScreenUtils.screenH(context);
    double width = 1;
    double height = 1;
    width = item.folderWidth.toDouble();
    height = item.folderHeight.toDouble();

    double imageScale = height / width;
    width = screenWidth;
    height = width*imageScale;
    String url = item?.getLocalPicUrl()??"";
    print("url:" + url);
    return ClipRect(
      child: Center(
        child: Container(
          width: screenWidth,
          height: height,
          alignment: Alignment.center,
          child: VgCacheNetWorkImage(
            url,
            imageQualityType: ImageQualityType.high,
            fit: BoxFit.cover,
            width: width,
            height: height,
            placeWidget: Container(
              color: Colors.transparent,
            ),
          ),
        ),
      ),
    );
  }


  ///底部门店以及文件夹信息
  Widget _toBottomWidget() {
    return Container(
      height: 56,
      margin: EdgeInsets.only(bottom: ScreenUtils.getBottomBarH(context)),
      padding: EdgeInsets.symmetric(horizontal: 12),
      child: GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: (){
          _assetsAudioPlayer?.pause();
          RouterUtils.pop(context);
          SmartHomePublishPage.navigatorPush(context, widget?.shid,
              "01", widget?.columnList, widget?.currentColumn, router: widget?.router,
              currentList: widget?.currentList, musicInfo: _currentBgm, musicList: _musicList);
        },
        child: Center(
          child: Container(
            height: 40,
            alignment: Alignment.center,
            decoration: BoxDecoration(
              color: Color(0XFF1890FF),
              borderRadius: BorderRadius.circular(4),
            ),
            child: Text(
              "下一步",
              style: TextStyle(
                  color: Colors.white,
                  fontSize: 15,
                  fontWeight: FontWeight.w600
              ),
            ),
          ),
        ),
      ),
    );
  }

  ///索引
  Widget _toIndexWidget() {
    //屏幕宽度
    double screenWidth = ScreenUtils.screenW(context);
    //左右间距
    double padding = 32;
    //间隔距离
    double gap = (_uploadList.length - 1) * 5.0;
    double width = (screenWidth - padding - gap)/_uploadList.length;
    _indexWidth = width;

    return Visibility(
      visible: _uploadList.length > 1,
      child: Container(
        height: 30,
        width: ScreenUtils.screenW(context),
        alignment: Alignment.center,
        color: Colors.black.withOpacity(0.4),
        padding: EdgeInsets.only(left: 16, right: 16,),
        child: ListView.separated(
            itemCount: _uploadList?.length ?? 0,
            shrinkWrap: true,
            scrollDirection: Axis.horizontal,
            physics: BouncingScrollPhysics(),
            itemBuilder: (BuildContext context, int index) {
              return _toIndexItemWidget(index);
            },
            separatorBuilder: (BuildContext context, int index) {
              return SizedBox(
                width: 5,
              );
            }),
      ),
    );
  }
  Widget _toIndexItemWidget(int index){
    //默认宽度
    return Center(
      child: Container(
        width: _indexWidth,
        height: 3,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(1.5),
          color: _selectIndex == index?Colors.white:Colors.white.withOpacity(0.3),
        ),
      ),
    );
  }

  void openPlayer(MusicListBean itemBean) async {
    print("22222${_playingAudio?.toString()??"9"}");
    print("22222_playingAudio?.metas?.id:${_playingAudio?.metas?.title}");
    print("22222, itemBean?.id:${itemBean?.mname}");
    print("22222 _isPlaying:${_isPlaying.toString()}");
    _currentBgm = itemBean;
    _assetsAudioPlayer.stop();
    VgHudUtils.show(context, "加载中");
    _playingAudio = Audio.network(
        itemBean.murl,
        metas: Metas(
          id: itemBean.id,
          title: itemBean.mname,
          artist: itemBean.author,
          album: itemBean.author,
        ),
        cached: true
    );
    setState(() {});
    try {
      await _assetsAudioPlayer.open(
        _playingAudio,
        autoStart: true,
        showNotification: false,
        loopMode: LoopMode.single,
        playInBackground: PlayInBackground.disabledRestoreOnForeground,
        audioFocusStrategy: AudioFocusStrategy.request(
            resumeAfterInterruption: true,
            resumeOthersPlayersAfterDone: true),
        headPhoneStrategy: HeadPhoneStrategy.pauseOnUnplug,
      );
    } catch (e) {
      print(e);
    }
  }
}
